package com.codebo.yunpicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.codebo.yunpicturebackend.common.ErrorCode;
import com.codebo.yunpicturebackend.config.CosClientConfig;
import com.codebo.yunpicturebackend.exception.BusinessException;
import com.codebo.yunpicturebackend.exception.ThrowUtils;
import com.codebo.yunpicturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIUploadResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FileManager
{
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    public UploadPictureResult uploadPicture(String key, MultipartFile multipartFile)
    {
        //1.校验图片合法性
        validPicture(multipartFile);
        //2.上传文件
        File file = null;
        String originalFilename = multipartFile.getOriginalFilename();
        String uuid = RandomUtil.randomString(16);
        String suffix = FileUtil.getSuffix(originalFilename);
        String uploadFileName = String.format("%s/%s_%s.%s", key, DateUtil.formatDate(new Date()), uuid, suffix);
        try
        {
            file = File.createTempFile(uploadFileName, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFileName, file);
            //3.解析文件上传结果
            CIUploadResult ciUploadResult = putObjectResult.getCiUploadResult();
            ImageInfo imageInfo = ciUploadResult.getOriginalInfo().getImageInfo();
            String format = imageInfo.getFormat();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();

            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(uploadFileName);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(multipartFile.getSize());
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(format);

            return uploadPictureResult;
        } catch (Exception e)
        {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally
        {
            //4.清理临时文件
            deleteTempFile(file);
        }


    }

    public void validPicture(MultipartFile multipartFile)
    {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "上传文件为空");
        //1.校验文件大小小
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024;
        ThrowUtils.throwIf(size > 2 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过2MB");
        //2.校验文件类型
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "png", "jpg", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(suffix), ErrorCode.PARAMS_ERROR, "仅支持上传 \"jpeg\", \"png\", \"jpg\", \"webp\"");
    }

    public void deleteTempFile(File file)
    {
        if (file == null)
        {
            return;
        }
        boolean del = FileUtil.del(file);
        if (!del)
        {
            log.error("删除临时文件失败，文件路径为：{}", file.getAbsolutePath());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除临时文件失败");
        }
    }

}
